package com.iflytek.xfapi.textModification.textRewriting;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 1、文本改写 Web API 调用示例
 * 2、运行前：请先填写Appid、APIKey、APISecret 相关信息
 */
public class TextRewriting {
    private String requestUrl = "https://api.xf-yun.com/v1/private/se3acbe7f";
    private String APPID = "7200bcb9";
    private String apiSecret = "YmQwMzRhZjE5Nzk4NDY0M2E2YTg3ZDUy";
    private String apiKey = "a553ca847559ef82045024f629ca650a";
    // 改写等级 <L1>  ~  <L6>  等级越高，改写程度越深
    private String LEVEL="<L6>";

    private static Gson gson = new Gson();


    /**
     * 工具类，传参只传要改写文本即可
     * @param TEXT
     * @return
     */
    public String getTEXT(String TEXT) {
        TextRewriting demo = new TextRewriting();
        String message = "";
        String textContent = "";
        try {
            String resp = demo.doRequest(TEXT);
            JSONObject jsonObject = JSON.parseObject(resp);

            // 打印和验证服务响应
            System.out.println("文本改写返回的结果：" + jsonObject);
            JSONObject headerObject = jsonObject.getJSONObject("header");
            message = headerObject.getString("message");

            // 反序列化JSON以获取Base64编码的文本
            JsonParse myJsonParse = gson.fromJson(resp, JsonParse.class);
            String base64Text = myJsonParse.payload.result.text;
            String textBase64Decode = new String(Base64.getDecoder().decode(base64Text), StandardCharsets.UTF_8);

            //截取字符串获取改写后的内容
            String result = extractContentBetweenFirstAndSecondQuotes(textBase64Decode);
            textContent = result;
        } catch (Exception e) {
            // 使用日志记录异常信息
            System.err.println("调用文本改写服务时发生异常: " + e.getMessage());
        }

        // 根据响应状态返回结果
        return "success".equals(message) ? textContent : "出错啦！请联系工作人员";
    }

    public static void main(String[] args) {
        String text = new TextRewriting().getTEXT("随着我国城市化脚步的不断加快，园林工程建设的数量也在不断上升，城市对于园林工程的质量要求也随之上升，");
        System.out.println(text);
    }

    /**
     * 截取字符串工具类
     * @param text
     * @return
     */
    public static String extractContentBetweenFirstAndSecondQuotes(String text) {
        int firstQuoteIndex = text.indexOf('\"'); // 找到第一个双引号的索引
        if (firstQuoteIndex == -1) return "123"; // 如果没有找到双引号，返回 "123"

        int secondQuoteIndex = text.indexOf('\"', firstQuoteIndex + 1); // 从第一个双引号之后找第二个双引号的索引
        if (secondQuoteIndex == -1) return "123"; // 如果没有找到第二个双引号，返回 "123"

        return text.substring(firstQuoteIndex + 1, secondQuoteIndex); // 截取并返回两个双引号之间的内容
    }

    /**
     * 请求主方法
     * @return 返回服务结果
     * @throws Exception 异常
     */
    public String doRequest(String TEXT) throws Exception {
        URL realUrl = new URL(buildRequetUrl());
        URLConnection connection = realUrl.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Content-type","application/json");

        OutputStream out = httpURLConnection.getOutputStream();
        String params = buildParam(TEXT);
        // System.out.println("params=>"+params);
        out.write(params.getBytes(StandardCharsets.UTF_8));
        out.flush();
        InputStream is;
        try{
            is = httpURLConnection.getInputStream();
        }catch (Exception e){
            is = httpURLConnection.getErrorStream();
            throw new Exception("make request error:"+"code is "+httpURLConnection.getResponseMessage()+readAllBytes(is));
        }
        return readAllBytes(is);
    }

    /**
     * 处理请求URL
     * 封装鉴权参数等
     * @return 处理后的URL
     */
    public String buildRequetUrl(){
        URL url;
        // 替换调schema前缀 ，原因是URL库不支持解析包含ws,wss schema的url
        String  httpRequestUrl = requestUrl.replace("ws://", "http://").replace("wss://","https://" );
        try {
            url = new URL(httpRequestUrl);
            //获取当前日期并格式化
            SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
            format.setTimeZone(TimeZone.getTimeZone("GMT"));
            String date = format.format(new Date());
            String host = url.getHost();
            if (url.getPort()!= 80 && url.getPort() != 443){
                host = host +":"+ url.getPort();
            }
            String builder = "host: " + host + "\n" +
                    "date: " + date + "\n" +
                    "POST " + url.getPath() + " HTTP/1.1";
            Charset charset = StandardCharsets.UTF_8;
            Mac mac = Mac.getInstance("hmacsha256");
            SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(charset), "hmacsha256");
            mac.init(spec);
            byte[] hexDigits = mac.doFinal(builder.getBytes(charset));
            String sha = Base64.getEncoder().encodeToString(hexDigits);

            String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
            String authBase = Base64.getEncoder().encodeToString(authorization.getBytes(charset));
            return String.format("%s?authorization=%s&host=%s&date=%s", requestUrl, URLEncoder.encode(authBase), URLEncoder.encode(host), URLEncoder.encode(date));

        } catch (Exception e) {
            throw new RuntimeException("assemble requestUrl error:"+e.getMessage());
        }
    }    /**
     * 组装请求参数
     * 直接使用示例参数，
     * 替换部分值
     * @return 参数字符串
     */
    private String  buildParam(String TEXT) throws UnsupportedEncodingException {
        String param = "{"+
                "    \"header\": {"+
                "        \"app_id\": \""+APPID+"\","+
                "        \"status\": 3"+
                "    },"+
                "    \"parameter\": {"+
                "        \"se3acbe7f\": {"+
                "            \"level\": \""+LEVEL+"\","+
                "            \"result\": {"+
                "                \"encoding\": \"utf8\","+
                "                \"compress\": \"raw\","+
                "                \"format\": \"json\""+
                "            }"+
                "        }"+
                "    },"+
                "    \"payload\": {"+
                "        \"input1\": {"+
                "            \"encoding\": \"utf8\","+
                "            \"compress\": \"raw\","+
                "            \"format\": \"plain\","+
                "            \"status\": 3,"+
                "            \"text\": \""+Base64.getEncoder().encodeToString(TEXT.getBytes(StandardCharsets.UTF_8))+"\""+
                "        }"+
                "    }"+
                "}";
        return param;
    }

    /**
     * 读取流数据
     *
     * @param is 流
     * @return 字符串
     * @throws IOException 异常
     */
    private String readAllBytes(InputStream is) throws IOException {
        byte[] b = new byte[1024];
        StringBuilder sb = new StringBuilder();
        int len;
        while ((len = is.read(b)) != -1){
            sb.append(new String(b, 0, len, StandardCharsets.UTF_8));
        }
        return sb.toString();
    }
    // JSON解析
    class JsonParse {
        public Header header;
        public Payload payload;
    }
    class Header{
        public int code;
        public String message;
        public String sid;
    }
    class Payload{
        //根据model的取值不同,名字有所变动。
        public Result result;
    }
    class Result{
        public String compress;
        public String encoding;
        public String format;
        public String text;
    }
}
